Math.easeInOutQuad = function(t, b, c, d) {
  t /= d / 2;
  if (t < 1) return c / 2 * t * t + b;
  t--;
  return -c / 2 * (t * (t - 2) - 1) + b;
};

export function scrollToElement(element, to, duration = 500, callback) {
  const start = element.scrollTop;
  const change = to - start;
  const increment = 20;
  let currentTime = 0;

  const animateScroll = () => {
    currentTime += increment;
    const val = Math.easeInOutQuad(currentTime, start, change, duration);
    element.scrollTop = val;

    if (currentTime < duration) {
      requestAnimationFrame(animateScroll);
    } else {
      element.scrollTop = to; // 确保最终位置准确
      callback?.();
    }
  };

  // 启动前先取消可能存在的已有动画
  cancelAnimationFrame(animateScroll.animationFrame);
  animateScroll.animationFrame = requestAnimationFrame(animateScroll);
}

// 使用示例：scrollToElement(document.querySelector('.scroll-box'), 0, 1000);
